<template>
	<el-main>
		<div class="">
			<div class="header">
				<el-button @click="start" type="primary" size="default">刷新</el-button>
				<el-button @click="editGroup()" type="primary" size="default">创建团队分组</el-button>
				<el-button @click="batchEditGroup" type="primary" size="default">批量修改成员分组</el-button>
			</div>
			<el-table :data="group" height="73vh">
				<template v-slot:empty>
					<el-empty image="https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/image/ojSass-empty.png" />
				</template>
				<el-table-column type="index"></el-table-column>
				<el-table-column prop="ID" label="分组ID"></el-table-column>
				<el-table-column prop="name" label="分组名称"></el-table-column>
				<el-table-column label="操作" class-name="text-right">
					<template #default="{ row }">
						<el-button size="default" type="primary" @click="editGroup(row.ID, row.name)">编辑</el-button>
						<el-button size="default" type="danger" @click="del(row.ID)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>

		<!-- 新增、编辑分组 -->
		<el-dialog v-model="dialogVisible" width="500px">
			<template #header>
				<span class="icon-text el-dialog__header-title">
					<el-icon class="text-primary">
						<Guide />
					</el-icon>
					{{ ID ? '修改' : '新增' }}
				</span>
			</template>
			<el-form label-width="150" size="default" @keyup.enter.native="submit">
				<el-form-item label="分组名称">
					<el-input class="add-user-form-item" v-model="name" placeholder="请输入名称" size="default">
					</el-input>
				</el-form-item>
				<el-form-item label="">
					<el-button size="default" @click="submit" type="primary">确定</el-button>
				</el-form-item>
			</el-form>
		</el-dialog>

		<!-- 批量修改成员分组 -->
		<el-dialog v-model="batchDialogVisible" width="800px">
			<template #header>
				<span class="icon-text el-dialog__header-title">
					<el-icon class="text-primary">
						<Guide />
					</el-icon>
					批量修改成员分组
				</span>
			</template>
			<el-form label-width="150px" :model="batchForm" :rules="rules" ref="batchFormRef" size="default">
				<el-form-item label="团队成员" prop="selectedUsers" required>
					<el-cascader placeholder="请选择团队成员" :style="{ width: '100%' }" v-model="batchForm.selectedUsers"
						:show-all-levels="false" :props="props" clearable filterable :options="options">
					</el-cascader>
				</el-form-item>
				<el-form-item label="团队分组" prop="selectedGroupId" required>
					<el-select placeholder="请选择团队分组" v-model="batchForm.selectedGroupId" clearable>
						<el-option v-for="item in group" :key="item.name" :label="item.name" :value="item.ID">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button size="default" @click="batchSubmit" type="primary">确定</el-button>
				</el-form-item>
			</el-form>
		</el-dialog>
	</el-main>
</template>

<script lang="ts" setup>
import { CascaderOption, ElMessage, ElMessageBox } from "element-plus";
import { computed, onMounted, ref } from "vue";
import { useStore } from "vuex";
import { asyncdelteamgroup, asyncfindteamusergroup, asyncselectteamuser, asyncteamaddteamgroup, asyncUpdateBatchTeamGroup } from "../../../api/index";
import { Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { toLocaleDateString } from "../../../util/time";

const props = { multiple: true }

const store = useStore(Storekey)
const user = computed<Studycodemodel.Iuser>(() => {
	return store.getters.getuser;
});
const teamId = computed(() => {
	return Number(user.value?.teamid)
})

const group = ref<Studycodemodel.Iteamusergroup[]>([])
async function start() {
	group.value = await asyncfindteamusergroup({ teamid: teamId.value });
}
onMounted(() => {
	start()
	getTeamUser()
})

function formatter(updatedAt: string | number | Date) {
	return toLocaleDateString(updatedAt);
}

async function del(ID: number) {
	ElMessageBox.confirm("确定要删除？", "提示", {
		confirmButtonText: "确定",
		cancelButtonText: "取消",
		type: "warning",
	})
		.then(async () => {
			await asyncdelteamgroup({ ID, teamid: teamId.value });
			ElMessage.success("操作成功");
			start();
		})
		.catch((e) => {
			ElMessage.error("删除失败", e);
			console.error(e);
		});
}

// 
const ID = ref<number | undefined>(undefined)
const name = ref()
const dialogVisible = ref(false)
function close() {
	dialogVisible.value = false
	start()
}
function editGroup(id?: number, v?: string) {
	ID.value = id
	name.value = v
	dialogVisible.value = true
}
async function submit() {
	try {
		await asyncteamaddteamgroup({ ID: ID.value, teamid: teamId.value, name: name.value, });
		ElMessage.success("修改成功");
		ID.value = undefined
		close()
	} catch (error) {
		ElMessage.error(`修改失败: ${error.message || error}`);
		console.error(error);
	}
}

// 批量修改相关状态及函数
const batchDialogVisible = ref(false);
const batchForm = ref({
	selectedUsers: [] as number[][],
	selectedGroupId: undefined as number | undefined
});
const rules = {
	selectedUsers: [{ required: true, message: '请选择团队成员', trigger: 'change' }],
	selectedGroupId: [{ required: true, message: '请选择团队分组', trigger: 'change' }]
};
const batchFormRef = ref();
async function batchEditGroup() {
	await getTeamUser();
	batchDialogVisible.value = true;
}
async function batchSubmit() {
	batchFormRef.value.validate(async (valid: boolean) => {
		if (valid) {
			try {
				const payload = {
					teamid: teamId.value,
					teamusergroupid: batchForm.value.selectedGroupId as number, // 分组ID
					userid: batchForm.value.selectedUsers.map(item => item[1]) // 只取第二项作为用户ID
				};
				await asyncUpdateBatchTeamGroup(payload)
				ElMessage.success("批量修改成功");
				// 
				batchFormRef.value.resetFields()
				getTeamUser();
				batchDialogVisible.value = false;
			} catch (error) {
				ElMessage.error(`批量修改失败: ${error.message || error}`);
				console.error(error);
			}
		} else {
			ElMessage.error("请完善表单信息");
		}
	});
}

// 获取团队成员
const teamuser = ref<Studycodemodel.Iteamuser[]>([]);
async function getTeamUser() {
	const data = await asyncselectteamuser({ teamid: teamId.value });
	teamuser.value = data.rows;
}

// 生成成员选项，用于级联选择器
const options = computed<CascaderOption[]>(() => {
	const groupOptions = group.value.map(e => ({
		label: e.name,
		value: e.ID,
		children: teamuser.value.filter(v => v.teamusergroupid === e.ID).map(u => ({
			label: u.user?.name,
			value: u.user?.ID
		}))
	}));
	const ungroupedOption = {
		label: "未分组",
		value: '',
		children: teamuser.value.filter(e => e.jurisdiction === "0" && !e.teamusergroupid).map(u => ({
			label: u.user?.name,
			value: u.user?.ID
		}))
	};
	return [ungroupedOption].concat(groupOptions);
});

</script>

<style csoped>
.header {
	margin-bottom: 20px;
}
</style>